import pandas as pd
import numpy as np
from sklearn.utils import shuffle
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn.cluster import MeanShift
from sklearn.cluster import DBSCAN

def draw(dataSet,labels,titles):
    # 生成数据

    X1 = []
    Y1 = []
    Z1 = []
    X2 = []
    Y2 = []
    Z2 = []
    X3 = []
    Y3 = []
    Z3 = []
    i = 0
    for row_index,preLabel in zip(dataSet.iterrows(),labels):
        i += 1
        if i > 3000:
            break
        try:
            preLineData  =  np.array(dataSet.iloc[row_index]).tolist()
        except:
            continue
        if preLabel == 0:
            X1.append(preLineData[0])
            Y1.append(preLineData[1])
            Z1.append(preLineData[2])
        elif preLabel == 1:
            X2.append(preLineData[0])
            Y2.append(preLineData[1])
            Z2.append(preLineData[2])
        else:
            X3.append(preLineData[0])
            Y3.append(preLineData[1])
            Z3.append(preLineData[2])
    fig = plt.figure()
    ax = Axes3D(fig)
    ax.scatter(X1,Y1,Z1)
    ax.scatter(X2,Y2,Z2)
    ax.scatter(X3,Y3,Z3)
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.title(titles)
    plt.show()


def draw_two(dataSet,labels,titles):
    plt.figure()
    plt.suptitle(titles)
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签\
    group = []
    X = []
    Y = []
    Z = []
    for data,i in zip(dataSet,labels):
        if i not in group:
            group.append(i)
            x_group = []
            x_group.append(data[0])
            y_group = []
            y_group.append(data[1])
            z_group = []
            z_group.append(data[2])
            X.append(x_group)
            Y.append(y_group)
            Z.append(z_group)
        else:
            X[group.index(i)].append(data[0])
            Y[group.index(i)].append(data[1])
            Z[group.index(i)].append(data[2])
    for x,y,z in zip(X,Y,Z):
        plt.scatter(x,y,z)
    plt.legend(loc="upper right")  # 显示图中的标签
    plt.xlabel("数据编号")
    plt.ylabel('结果分类')
    plt.show()

def clipData(Data,row,lables):
    resaultList = []
    for i in range(row):
        if Data.loc[i,'activity'] in lables:
            resaultList.append(np.array(Data.loc[i,:]).tolist())
    data = pd.DataFrame(resaultList)
    data.columns = ['SequenceName', 'Tagidentificator', 'timestamp', 'dateFORMAT', 'x_coordinate', 'y_coordinate','z_coordinate', 'activity']
    return data

def loadData(fileName):
    Data = pd.read_csv(fileName,names=['SequenceName','Tagidentificator','timestamp','dateFORMAT','x_coordinate','y_coordinate','z_coordinate','activity'])
    Data.dropna(axis=0)
    row,columns = Data.shape
    Data = clipData(Data,row,['sitting','lying down'])
    Data = shuffle(Data)
    dataSet = Data.iloc[:,4:7]
    return dataSet

#KMeans算法
def myKMeans(dataSet,n_clusters):
    kmeans = KMeans(n_clusters)  # n_clusters:number of cluster
    kmeans.fit(dataSet)
    draw(dataSet,kmeans.labels_ ,titles="KMeans算法分类效果图")

def myMeanShift(dataSet):
    meanshift = MeanShift(bandwidth=1)  # 带宽
    meanshift.fit(dataSet)
    draw_two(dataSet,meanshift.labels_ ,titles='MeanShift算法分类效果图')

def myDBSCAN(dataSet):
    db = DBSCAN(eps=0.3, min_samples=10)
    db.fit(dataSet)
    draw(dataSet,db.labels_,titles='DBSCAN算法分类效果图')

if __name__ == "__main__":
    fileName = 'ConfLongDemo_JSI.csv'
    dataSet = loadData(fileName)
    myKMeans(dataSet,3)
    myDBSCAN(dataSet)

    #myMeanShift(dataSet)
